package com.chajia.pipeline;

import com.chajia.dao.PriceDao;
import com.chajia.dao.ProductDao;
import com.chajia.model.Price;
import com.chajia.model.Product;
import com.chajia.util.LogUtil;
import com.chajia.util.Transaction;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-12-28
 * Time: 上午7:27
 * To change this template use File | Settings | File Templates.
 */
public class MysqlPipeline implements Pipeline {
    public static Class clazz= MysqlPipeline.class;
    ProductDao productDao = new ProductDao();
    PriceDao priceDao=new PriceDao();
    @Override
    public void process(ResultItems resultItems, Task task) {
        //To change body of implemented methods use File | Settings | File Templates.

        String pid= resultItems.get("pid");
        if (pid!=null){
        String title=resultItems.get("title");
        String url=resultItems.get("url");
        String img=resultItems.get("img");
        String pr=resultItems.get("price");

        Product product=new Product(pid,title,url,img);

        try {
            if(!productDao.isExist(product.getPid())){
            synchronized (product) {if(!productDao.insert(product)){
                LogUtil.error(clazz,"插入产品失败");
            }
            }
            }
            Price price=new Price(productDao.getId(pid),pr);
            if(!priceDao.insert(price)){
                LogUtil.error(clazz,"插入价格失败");
            }

        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        finally {
            Transaction.closeSession(true);
        }
        }
    }
}
